package com.easyboot.web.monitor.controller;

import cn.hutool.core.convert.Convert;
import com.easyboot.framework.domain.ResultAdaptDto;
import com.easyboot.utils.log.LoggerHelper;
import com.easyboot.framework.domain.DataTableDto;
import com.easyboot.framework.domain.KeyValueInt64Dto;
import com.easyboot.framework.domain.TestDto;
import com.easyboot.framework.utils.spring.SpringUtils;
import com.easyboot.framework.core.ActionResult;
import com.easyboot.framework.core.BaseController;
import com.easyboot.framework.core.RequestHelper;
import com.easyboot.web.monitor.domain.MonitorJob;
import com.easyboot.web.monitor.jobs.JobTest;
import com.easyboot.web.monitor.service.MonitorJobLogService;
import com.easyboot.web.monitor.service.MonitorJobService;
import com.easyboot.web.system.service.SysDictionaryService;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yushuo
 * @className
 * @descripton TODO
 * @date 2021/6/3 14:24
 **/
@Controller
@RequestMapping("/monitor/job")
public class JobController extends BaseController {

    @Autowired
    private RequestHelper requestHelper;
    @Autowired
    private MonitorJobService jobService;
    @Autowired
    private MonitorJobLogService jobLogService;
    @Autowired
    private SysDictionaryService dicService;
    @Autowired
    private Scheduler scheduler;
    /**
    *
     * @author yushuo
     * @description 执行任务
     * @date 14:26 2021/6/3
     * @param
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/index")
    @RequiresPermissions("monitor:job:view")
    public ActionResult index(){
        return view();
    }

    /**
    *
     * @author yushuof
     * @description 获取任务列表
     * @date 15:06 2021/6/3
     * @param
     * @return com.easyboot.framework.web.ActionResult
    **/

    @PostMapping("/getPageList")
    @RequiresPermissions("monitor:job:view")
    public ActionResult getPageList(DataTableDto dto){

        DataTableDto data= jobService.getPageList(dto);
        return json(data);
    }

    /**
    *
     * @author yushuo
     * @description 测试
     * @date 17:30 2021/6/24
     * @param [result]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/test")
    public ActionResult test(TestDto reqDto){

        TestDto respDto=new TestDto();
        respDto.setCode(1);
        respDto.setName("response name");
        ResultAdaptDto result=new ResultAdaptDto();
        result.put("name",respDto.getName());
        result.put("code",respDto.getCode());
        return json(result);
    }

    /**
     * 任务表单
     * @return
     */
    @GetMapping("/form")
    @RequiresPermissions(value = {"monitor:job:add","monitor:job:edit"},logical = Logical.OR)
    public ActionResult form(Model model){

        String jobId=requestHelper.getString("jobId","");
        model.addAttribute("jobId",jobId);
        List<KeyValueInt64Dto> dictList=dicService.getSonDictSelect("quartz_group");
        model.addAttribute("jobGroups",dictList);
        return view();
    }

    /**
     * @author yushuo
     * @description 获取任务详情
     * @date 17:42 2021/6/21
     * @param [id]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/getModel")
    @RequiresPermissions(value = {"monitor:job:add","monitor:job:edit"},logical = Logical.OR)
    public ActionResult getModel(String id){
         MonitorJob model=jobService.getModel(Convert.toLong(id));
         Hashtable<String,Object> data=new Hashtable<>();
         data.put("model",model);
         return json(data);
    }

    /**
     * @author yushuo
     * @description 提交任务
     * @date 15:13 2021/6/23
     * @param [job]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @PostMapping("save")
    @RequiresPermissions(value = {"monitor:job:add","monitor:job:edit"},logical = Logical.OR)
    public ActionResult save(MonitorJob job)throws SchedulerException{
        jobService.saveJob(job, requestHelper.getUserOwnInfo());
        return ok("任务已添加");
    }

    /**
     * @author yushuo
     * @description 删除任务
     * @date 15:14 2021/6/23
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/removeAll")
    @RequiresPermissions("monitor:job:delete")
    public ActionResult removeAll(){
        long jobId=requestHelper.getInt64("id",0L);
        if(jobId==0){
            return error("任务删除失败");
        }
        jobService.deletJob(jobId);
        return ok("任务已删除");
    }

    /**
     * @author yushuo
     * @description 执行任务
     * @date 15:22 2021/6/23
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/run")
    @RequiresPermissions("monitor:job:excute")
    public ActionResult run(){
        long jobId=requestHelper.getInt64("id",0L);
        if(jobId==0){
            return error("任务执行失败");
        }
        try{
            jobService.runJob(jobId);
        }catch (SchedulerException ex){
            LoggerHelper.error(ex.getMessage());
            return error("任务执行失败");
        }


        return ok("任务执行中");
    }
    /**
     * @author yushuo
     * @description 停止任务
     * @date 13:45 2021/6/22
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("stop")
    @RequiresPermissions("monitor:job:stop")
    public ActionResult stop(){

        long jobId=requestHelper.getInt64("id",0L);
        if(jobId==0){
            return error("任务停止失败");
        }
        try{
            jobService.stopJob(jobId);
        }catch (SchedulerException ex){
            LoggerHelper.error(ex.getMessage());
            return error("任务停止失败");
        }


        return ok("任务已停止");
    }


    /**
     * @author yushuo
     * @description 恢复任务
     * @date 14:38 2021/6/23
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @RequiresPermissions("monitor:job:resume")
    @GetMapping("/resume")
    public ActionResult resume(){
        long jobId=requestHelper.getInt64("id",0L);
        if(jobId==0){
            return error("任务恢复失败");
        }
        try{
            jobService.resumeJob(jobId);
        }catch (SchedulerException ex){
            LoggerHelper.error(ex.getMessage());
            return error("任务恢复失败");
        }

        return ok("任务已恢复");
    }

    /**
    *
     * @author yushuo
     * @description  执行日记
     * @date 15:28 2021/6/23
     * @param [model]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @RequiresPermissions("monitor:job:log")
    @GetMapping("/jobLog")
    public ActionResult jobLog(ModelMap model){

        long jobId=requestHelper.getInt64("id",0L);
        model.addAttribute("jobId",jobId);
        return view();
    }

    /**
     * @author yushuo
     * @description 执行日志
     * @date 15:13 2021/6/24
     * @param [dto]
     * @return com.easyboot.framework.web.ActionResult
    **/
    @RequiresPermissions("monitor:job:log")
    @PostMapping("/jobLogData")
    public ActionResult jobLogData(DataTableDto dto){
        long jobId=requestHelper.getInt64("jobId",0L);
        if(jobId==0){
            return json(dto);
        }
        dto=jobLogService.jobLogData(dto,jobId);
        return json(dto);
    }

    /**
     * @author yushuo
     * @description 执行日志
     * @date 15:13 2021/6/24
     * @param [dto]
     * @return com.easyboot.framework.web.ActionResult
     **/
    @RequiresPermissions("monitor:job:log")
    @GetMapping("/clearJobLog")
    public ActionResult clearJobLog(){
        long jobId=requestHelper.getInt64("jobId",0L);
        if(jobId==0){
            return error("禁止删除");
        }
        jobLogService.clearJobLog(jobId);
        return ok("日志已删除");
    }


    /**
     * @author yushuo
     * @description 测试获取getbean
     * @date 16:21 2021/6/22
     * @param []
     * @return com.easyboot.framework.web.ActionResult
    **/
    @GetMapping("/getbeantest")
    public ActionResult getBean(){
        ApplicationContext application= SpringUtils.getApplicationContext();
        if(application==null){
            return error("applicationContext初始化失败");
        }
        JobTest qjob=application.getBean("JobTest", JobTest.class);
        if(qjob==null){
            return error("获取bean失败");
        }
//        JobExecutionContext jobExecutionContext=scheduler.getexecutionContext();
//        jobExecutionContext.put("source","this source from getbean controller");
       // try{
            qjob.test("this source from getbean controller");
//        }catch(JobExecutionException ex){
//            return error(ex.getMessage());
//        }

        return ok("获取bean成功");
    }


}
